package com.example.nophase.activity.staff;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.Toolbar;

import com.example.nophase.R;
import com.example.nophase.adapter.ApplyForListAdapter;
import com.example.nophase.api.RequstCommonApi;
import com.example.nophase.base.BaseActivity;
import com.example.nophase.common.BaseCallBack;
import com.example.nophase.common.BasePage;
import com.example.nophase.common.BaseResp;
import com.example.nophase.common.LoginManager;
import com.example.nophase.entity.ApplyForListDTO;
import com.example.nophase.entity.SysUserVO;
import com.example.nophase.utils.HttpUtils;
import com.scwang.smartrefresh.header.WaterDropHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.BallPulseFooter;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Response;

public class ApplyForListActivity extends BaseActivity {
    @BindView(R.id.applyfor_toolbar)
    Toolbar applyforToolbar;
    public int page = 1;
    @BindView(R.id.applyfor_lv)
    ListView applyforLv;
    @BindView(R.id.applyfor_list_refreshLayout)
    SmartRefreshLayout applyforListRefreshLayout;
    @BindView(R.id.progressbar)
    ProgressBar progressbar;
    @BindView(R.id.iv_background)
    ImageView ivBackground;
    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    private List<ApplyForListDTO> resultList = new ArrayList<>();
    private ApplyForListAdapter adapter;
    private int dataSize;
    private String code;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_apply_for);
        ButterKnife.bind(this);
        Intent intent = getIntent();
        code = intent.getStringExtra("code");
        initData(code);
        setToolbar();
        adapter = new ApplyForListAdapter(resultList, this);
        applyforLv.setAdapter(adapter);
        adapter.notifyDataSetChanged();
        applyforLv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                String status = resultList.get(position).getStatus();
                System.out.println("=======" + status);
                if (status.equals("审核中")) {

                    showWarningDialog(resultList.get(position).getId());//删除工单
                } else {
                    showErrorDialog();//提示工单完成禁止删除
                }
                return true;
            }
        });
        applyforLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if(code.equals("已完成")){
                    showAuditPeopleDialog("终审人:"+resultList.get(position).getCurrentUsername());
                }else{
                    showAuditPeopleDialog("当前审核人:"+resultList.get(position).getCurrentUsername());
                }

            }
        });

        applyforListRefreshLayout.setRefreshHeader(new WaterDropHeader(this));
        applyforListRefreshLayout.setRefreshFooter(new BallPulseFooter(this));
        setRefreshListener();
    }

    public void deleteItem(int id) {
        progressbar.setVisibility(View.VISIBLE);
        Call<BaseResp<Object>> call = HttpUtils.getInstance().getApiService(RequstCommonApi.class).deleteApplyFor(id);
        call.enqueue(new BaseCallBack<BaseResp<Object>>() {
            @Override
            public void onSuccess(Response<BaseResp<Object>> response) throws Exception {
                progressbar.setVisibility(View.GONE);
                ivBackground.setVisibility(View.GONE);
                System.out.println("=======" + response.body().toString());
                Toast.makeText(ApplyForListActivity.this, "删除成功", Toast.LENGTH_SHORT).show();
                initData(code);

            }

            @Override
            public void onFailure(String message) {

            }
        });
    }

    //禁止删除提示框
    public void showErrorDialog() {
        LayoutInflater factory = LayoutInflater.from(this);//提示框
        final View view = factory.inflate(R.layout.dialog_layout, null);//这里必须是final的

        AlertDialog dialog = new AlertDialog.Builder(this)
                .setTitle("提醒")//提示框标题
                .setIcon(R.drawable.apply_for_from)
                .setMessage("此申请已完成审批禁止删除")
                .setPositiveButton("确定",//提示框的两个按钮
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        }).create();
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    }


    //当前审核人提示框
    public void showAuditPeopleDialog(String auditName) {
        LayoutInflater factory = LayoutInflater.from(this);//提示框
        final View view = factory.inflate(R.layout.dialog_layout, null);//这里必须是final的

        AlertDialog dialog = new AlertDialog.Builder(this)
                .setTitle("提醒")//提示框标题
                .setIcon(R.drawable.apply_for_from)
                .setMessage(auditName)
                .setPositiveButton("确定",//提示框的两个按钮
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        }).create();
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    }


    //显示提醒框
    public void showWarningDialog(int applyForListId) {
        LayoutInflater factory = LayoutInflater.from(this);//提示框
        final View view = factory.inflate(R.layout.dialog_layout, null);//这里必须是final的
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setTitle("是否删除")//提示框标题
                .setIcon(R.drawable.apply_for_from)
                .setMessage("是否删除正在审请中的工单")
                .setPositiveButton("确定",//提示框的两个按钮
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                deleteItem(applyForListId);
                                dialog.dismiss();
                            }
                        })
                .setNegativeButton("取消", null).create();
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    }

    private void setRefreshListener() {

        applyforListRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                refreshLayout.autoRefresh();//自动刷新

                page = 1;
                SysUserVO sysUserVO = LoginManager.getUserInfo(ApplyForListActivity.this);
                String uuid = sysUserVO.getUuid();
                HttpUtils.getInstance().setAuthToken(LoginManager.getToken(ApplyForListActivity.this));
                ivBackground.setVisibility(View.VISIBLE);
                resultList.clear();
                adapter.notifyDataSetChanged();
                Call<BaseResp<BasePage<ApplyForListDTO>>> call = HttpUtils.getInstance().getApiService(RequstCommonApi.class).loadApplyforList(uuid, code, 10, 1);
                call.enqueue(new BaseCallBack<BaseResp<BasePage<ApplyForListDTO>>>() {
                    @Override
                    public void onSuccess(Response<BaseResp<BasePage<ApplyForListDTO>>> response) throws Exception {
                        refreshLayout.finishRefresh();//结束刷新
                        List<ApplyForListDTO> list = response.body().getData().getRecords();
                        dataSize = list.size();
                        if (dataSize > 0) {
                            ivBackground.setVisibility(View.GONE);
                        }
                        for (ApplyForListDTO item : list) {
                            resultList.add(item);
                            adapter.notifyDataSetChanged();
                        }

                    }

                    @Override
                    public void onFailure(String message) {

                    }
                });
            }
        });
        applyforListRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;
                SysUserVO sysUserVO = LoginManager.getUserInfo(ApplyForListActivity.this);
                String uuid = sysUserVO.getUuid();
                HttpUtils.getInstance().setAuthToken(LoginManager.getToken(ApplyForListActivity.this));
                Call<BaseResp<BasePage<ApplyForListDTO>>> call = HttpUtils.getInstance().getApiService(RequstCommonApi.class).loadApplyforList(uuid, code, 10, page);
                call.enqueue(new BaseCallBack<BaseResp<BasePage<ApplyForListDTO>>>() {
                    @Override
                    public void onSuccess(Response<BaseResp<BasePage<ApplyForListDTO>>> response) throws Exception {
                        refreshLayout.finishLoadMore();//结束加载
                        List<ApplyForListDTO> list = response.body().getData().getRecords();
                        if (list.size() != 0) {
                            dataSize = list.size();

                            for (ApplyForListDTO item : list) {
                                resultList.add(item);
                            }
                            adapter.notifyDataSetChanged();

                        } else {
                            Toast.makeText(ApplyForListActivity.this, "没有更多数据了", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(String message) {

                    }
                });

            }


        });
    }

    private void initData(String status) {
        SysUserVO sysUserVO = LoginManager.getUserInfo(this);
        String uuid = sysUserVO.getUuid();
        HttpUtils.getInstance().setAuthToken(LoginManager.getToken(this));
        progressbar.setVisibility(View.VISIBLE);
        Call<BaseResp<BasePage<ApplyForListDTO>>> call = HttpUtils.getInstance().getApiService(RequstCommonApi.class).loadApplyforList(uuid, status, 10, 1);
        call.enqueue(new BaseCallBack<BaseResp<BasePage<ApplyForListDTO>>>() {
            @Override
            public void onSuccess(Response<BaseResp<BasePage<ApplyForListDTO>>> response) throws Exception {
                progressbar.setVisibility(View.GONE);
                List<ApplyForListDTO> list = response.body().getData().getRecords();
                dataSize = list.size();
                if (dataSize > 0) {
                    ivBackground.setVisibility(View.GONE);
                }
                resultList.clear();
                for (ApplyForListDTO item : list) {
                    resultList.add(item);
                }
                adapter.notifyDataSetChanged();
                applyforListRefreshLayout.finishRefresh(2000/*,false*/);//传入false表示刷新失败

            }

            @Override
            public void onFailure(String message) {

            }
        });
    }

    private void setToolbar() {
        applyforToolbar.setNavigationIcon(R.drawable.ic_left_black_24dp);
        applyforToolbar.setTitle("");
        if (code.equals("已完成")) {
            toolbarTitle.setText("已终审");
        }
        setSupportActionBar(applyforToolbar);
        getSupportActionBar().setHomeButtonEnabled(true);

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {

            case android.R.id.home:
                this.finish();
                return true;

        }
        return super.onOptionsItemSelected(item);
    }

}
